<script setup>
import {onMounted, reactive, ref} from "vue";
import router from "@/router/index.js";
import {getToken, removeToken} from "@/api/cookie.js";
import {isTokenExpired} from "@/api/utils.js";
import {detailUserService, logoutUserService} from "@/api/user.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 默认是未登录，没有消息的状态
const isLogin = ref(false)
const userInfo = reactive({
  headShot: "",
  nickName: ""
})

function goLogin() {
  router.push("/user/system")
}

onMounted(() => {
  checkIsLogin()
})

async function checkIsLogin() {
  const token = getToken()
  if (token && !isTokenExpired(token)) {
    // 此时说明token有效，将状态改为登录状态
    const userInfoResult = await detailUserService()
    Object.assign(userInfo, userInfoResult.data)
    isLogin.value = true
  }
}

async function handleLogout() {
  try {
    await ElMessageBox.confirm(
        '确定要退出登录吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
    await logoutUserService()
    removeToken()
    isLogin.value = false
    ElMessage.success("用户成功退出登录！")
    await router.push("/user/login")
  } catch (error) {
    if (error === "cancel") {
    }
  }
}

function goMyExam() {
  router.push("/user/system/some/contest")
}

function goUserDetail() {
  router.push("/user/system/user-info")
}

function goOther() {
  ElMessage.warning("尽请期待!");
}

// websocket 连接器
const token = getToken();
const socket = new WebSocket(`ws://127.0.0.1:8000/websocket/contest/notify?token=${token}`);

socket.onmessage = function (event) {
  const message = event.data;
  ElMessage({
    message: message,
    type: 'warning',
    showClose: true,
    plain: true,
    duration: 0
  })
};

socket.onopen = function () {
  console.log("WebSocket connection established.");
};

socket.onclose = function () {
  console.log("WebSocket connection closed.");
};

function goMessage() {
  router.push("/user/system/message")
}
</script>

<template>
  <div class="oj-navbar">
    <div class="oj-navbar-menus">
      <img class="oj-navbar-logo" src="@/assets/images/logo.png"/>
      <el-menu router class="oj-navbar-menu" mode="horizontal">
        <el-menu-item index="/user/system/question">题库</el-menu-item>
        <el-menu-item index="/user/system/contest">竞赛</el-menu-item>
        <!--        <el-menu-item @click="goOther()">刷题</el-menu-item>-->
        <!--        <el-menu-item @click="goOther()">练题</el-menu-item>-->
        <!--        <el-menu-item @click="goOther()">讨论</el-menu-item>-->
        <!--        <el-menu-item @click="goOther()">面试</el-menu-item>-->
      </el-menu>
    </div>
    <div class="oj-navbar-users">
      <img v-if="isLogin" class="oj-message" @click="goMessage" src="@/assets/images/no_message.png"/>
      <el-dropdown v-if="isLogin">
        <div class="oj-navbar-name">
          <img class="oj-head-image" v-if="isLogin" :src="userInfo.headShot"/>
          <span>{{ userInfo.nickName }}</span>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goUserDetail">
              <div class="oj-navabar-item">
                <span>个人中心</span>
              </div>
            </el-dropdown-item>
            <el-dropdown-item @click="goMyExam">
              <div class="oj-navabar-item">
                <span>我的竞赛</span>
              </div>
            </el-dropdown-item>
            <el-dropdown-item>
              <div class="oj-navabar-item">
                <span @click="handleLogout">退出登录</span>
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <span class="oj-navbar-login-btn" v-if="!isLogin" @click="goLogin">登录</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.oj-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
  position: relative;
  max-width: 1520px;
  margin: 0 auto;

  .oj-navbar-menus {
    display: flex;
    align-items: center;
    height: 60px;

    .el-menu-item {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 20px;
      color: #222222;
      line-height: 28px;
      text-align: center;
      width: 42px;
      text-align: left;
      margin-right: 25px;
    }
  }

  .oj-navbar-logo {
    width: 38px;
    height: 38px;
    background: white;
    border-radius: 8px;
    cursor: pointer;
    object-fit: contain;
    margin-right: 59px;
  }

  .oj-navbar-menu {
    width: 600px;
    border: none;

    .el-menu-item {
      font-family: "Roboto", "PingFangSC", "PingFang SC", Arial, sans-serif;
      font-weight: 500;
      font-size: 18px;
      color: #444;
      line-height: 28px;
      text-align: center;
      margin-right: 45px;
      padding: 4px 6px;
      border-radius: 8px;
      transition: color 0.3s, transform 0.2s;
      outline: none;
      box-shadow: none;

      &:hover {
        color: #4a90e2;
        transform: scale(1.1);
        font-weight: bold;
        background-color: transparent;
      }

      &:focus {
        outline: none;
        box-shadow: none;
      }

      &:focus-visible {
        outline: none;
      }

      &.is-active {
        color: white;
        font-weight: bold;
        padding: 8px 16px;
        border-radius: 8px;
        text-decoration: none;
        background-color: transparent !important;
        border-bottom: none !important;
        box-shadow: none !important;
      }
    }
  }

  .oj-navbar-users {
    display: flex;
    align-items: center;
    height: 60px;
  }

  .oj-navbar-login-btn {
    line-height: 60px;
    display: inline-block;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #222222;
    text-align: center;
    cursor: pointer;

    .line {
      display: inline-block;
      width: 25px;
    }
  }

  .oj-message {
    cursor: pointer;
    width: 30px;
    height: 30px;
    margin-right: 10px;
    margin-bottom: 2px;
  }

  .oj-head-image {
    width: 35px;
    height: 35px;
    border-radius: 20px;
    margin-right: 10px;
  }

  .oj-navbar-name {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-weight: 400;
    color: #000;
    margin-left: 15px;
    margin-right: 30px;
    font-size: 18px;
    width: 100px;
    outline: none;
    margin-bottom: 5px;
  }

  .oj-navbar-name:focus {
    outline: none;
  }

  .oj-navabar-item {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 32px;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 1px;
    border-bottom: 1px solid #ccc;
    margin-bottom: 10px;
  }
}
</style>